// 工具函数模块

use std::time::{SystemTime, UNIX_EPOCH};
use log::info;

/// 获取当前时间戳（毫秒）
pub fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// 格式化字节大小为人类可读格式
pub fn format_bytes(bytes: u64) -> String {
    const UNITS: [&str; 6] = ["B", "KB", "MB", "GB", "TB", "PB"];
    let mut size = bytes as f64;
    let mut unit_index = 0;

    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
        size /= 1024.0;
        unit_index += 1;
    }

    format!("{:.2} {}", size, UNITS[unit_index])
}

/// 检查字符串是否为有效标识符
pub fn is_valid_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }

    let first_char = s.chars().next().unwrap();
    if !first_char.is_alphabetic() && first_char != '_' {
        return false;
    }

    s.chars().all(|c| c.is_alphanumeric() || c == '_')
}

/// 安全的字符串截断
pub fn truncate_string(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}

/// 生成唯一标识符
pub fn generate_unique_id() -> String {
    use rand::Rng;
    let mut rng = rand::thread_rng();
    format!("{:x}", rng.gen::<u64>())
}

/// 验证文件路径安全性
pub fn is_safe_path(path: &str) -> bool {
    let path = std::path::Path::new(path);
    
    // 检查是否包含危险字符或路径遍历
    !path.to_string_lossy().contains("..") &&
    !path.to_string_lossy().contains("//") &&
    !path.to_string_lossy().contains("\\\\")
}

/// 计算哈希值（简单实现）
pub fn simple_hash(s: &str) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    
    let mut hasher = DefaultHasher::new();
    s.hash(&mut hasher);
    hasher.finish()
}

/// 性能计时器
pub struct PerformanceTimer {
    start_time: std::time::Instant,
    operation_name: String,
}

impl PerformanceTimer {
    pub fn new(operation_name: &str) -> Self {
        PerformanceTimer {
            start_time: std::time::Instant::now(),
            operation_name: operation_name.to_string(),
        }
    }

    pub fn stop(self) {
        let duration = self.start_time.elapsed();
        info!("{} completed in {:.2}ms", self.operation_name, duration.as_millis());
    }
}

impl Drop for PerformanceTimer {
    fn drop(&mut self) {
        if !std::thread::panicking() {
            let duration = self.start_time.elapsed();
            info!("{} completed in {:.2}ms", self.operation_name, duration.as_millis());
        }
    }
}

/// 宏：性能测量
#[macro_export]
macro_rules! measure_time {
    ($name:expr, $block:block) => {
        {
            let _timer = $crate::core::utils::PerformanceTimer::new($name);
            $block
        }
    };
}